<?php
namespace stock\other;
class RedisDemo{ 
    /** @var \Redis */
    protected $handler = null;
    protected $config  = array(
        'host'         => '127.0.0.1', // redis主机
        'port'         => 6379, // redis端口
        'password'     => '', // 密码
        'expire'       => 3600, // 有效期(秒)
        'timeout'      => 0, // 超时时间(秒)
        'persistent'   => true, // 是否长连接
        'session_name' => '', // sessionkey前缀
	);
    private $expire_time=60*60*10;
	private $pre='';




    public function open()
    {
        // 检测php环境
        if (!extension_loaded('redis')) {
            throw new Exception('not support:redis');
        }
        $this->handler = new \Redis;

        // 建立连接
        $func = $this->config['persistent'] ? 'pconnect' : 'connect';
        $this->handler->$func($this->config['host'], $this->config['port'], $this->config['timeout']);

        if ('' != $this->config['password']) {
            $this->handler->auth($this->config['password']);
        }
        return true;
    }

    public function __construct(){
		/*
		$config = new Config("site_config");
		$site_config   = $config->getInfo();
		$redis_info=$site_config['redis'];
		$this->config['port']=$redis_info['redis_port'];
		$this->config['host']=$redis_info['redis_host'];
		$this->config['password']=$redis_info['redis_pwd'];
		$this->pre=$redis_info['pre']; 
		*/ 
		$this->pre='unitop_express_';   	
    	if(!$this->handler){
    		$this->open();
    	}
    	
    }


    public function close()
    {
        $this->handler->close();
        $this->handler = null;
        return true;
    }

 
    public function get($sessID)
    {
        return $this->handler->get($sessID);
    }


    public function set($sessID, $sessData,$time='')
    {
        $ex_time=$time ? $time : $this->expire_time;
        return $this->handler->set($sessID, $sessData,$ex_time);

    }

    public function exists($key){
        $n_key=$this->pre.$key;
        return $this->handler->exists((string)$n_key);
    }

    public function destroy($sessID)
    {
        $this->handler->delete($this->pre.$sessID);
    }
    public function flushall(){
        $this->handler->flushall();
    }

    /**
     * Session 垃圾回收
     * @access public
     * @param string $sessMaxLifeTime
     * @return bool
     */
    public function gc($sessMaxLifeTime)
    {
        return true;
    }	
}	